package org.wxd.account.engine.user;

import org.wxd.account.api.user.UserQueryService;
import org.wxd.account.api.user.dto.UserGetRequest;
import org.wxd.account.api.user.dto.UserListRequest;
import org.wxd.account.api.user.dto.UserRecord;
import org.wxd.account.domain.user.User;
import org.wxd.common.utils.Assert;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * Created by wangxd on 2015/10/30.
 */
public class UserQueryServiceImpl implements UserQueryService{

    @PersistenceContext
    private EntityManager em;

    public UserRecord get(UserGetRequest request) {
        Assert.notNull(request, "request must not be null.");
        User user = em.createQuery("SELECT o FROM User o WHERE o.id = :id",User.class)
                .setParameter("id", request.userId())
                .getSingleResult();
        return user == null ? null : UserHelper.asUserRecord(user);
    }

    public List<UserRecord> list(UserListRequest request) {
        return UserHelper.asUserRecordList(em.createQuery("SELECT o FROM User o WHERE 1=1 ",User.class).getResultList());
    }

}
